const fs = require('fs')
const path = require('path')
const { nanoid } = require('nanoid')
const { isFileExisted } = require('../utils/netTools')

class OrdersController {
	async filterOrders(req, res, next) {
		let myPath = path.join(__dirname, '../data/orders.json');
		const ordersList = JSON.parse(fs.readFileSync(myPath, 'utf8'));
		const { userId } = req.query
		const filteredOrdersList = ordersList.filter(order => order.userId == userId)
		if (filteredOrdersList.length > 0) {
			res.json({
				code: 200,
				msg: '查询订单成功',
				data: filteredOrdersList
			})
		} else {
			res.json({
				code: 403,
				msg: '查询订单失败'
			})
		}
	}

	async addOrder(req, res, next) {
		const { seqNo, userId, movieId } = req.body;

		const cinemaDetailPath = path.join(__dirname, `../data/cinemaDetail`);

		const cinemaDetailNames = fs.readdirSync(cinemaDetailPath, 'utf-8')

		const cinemaPaths = cinemaDetailNames.map(cinemaDetailName => path.join(__dirname, `../data/cinemaDetail/${cinemaDetailName}`))


		try {
			// 获取电影
			const moviePath = path.join(__dirname, `../data/detailmovie/${movieId}.json`);

			await isFileExisted(moviePath);
			const movie = JSON.parse(fs.readFileSync(moviePath, 'utf8'));

			for (let cinemaPath of cinemaPaths) {
				const cinema = JSON.parse(fs.readFileSync(cinemaPath, 'utf8'));
				const showData = cinema.showData
				const cinemaData = cinema.cinemaData
				if (showData) {
					for (let m of cinema.showData.movies) {
						if (m.id == movieId) {
							for (let show of (m.shows || [])) {
								for (let plist of show.plist) {
									if (plist.seqNo == seqNo) {
										const { dur } = m
										const { dt, tm, lang, th } = plist

										const date = new Date(`${dt}T${tm}`)
										const startTime = date.getTime()
										date.setMinutes(date.getMinutes() + +dur)
										const endTime = date.getTime()

										console.log(startTime, endTime);
										console.log('match');
										const order = {
											"orderId": nanoid(),
											"userId": userId,
											"orderStatus": "未完成",
											qrcode: nanoid(),
											orderTime: Date.now(),
											payStatus: 0,
											count: 1,
											price: plist.vipPrice || "30",
											cinema: {
												"id": showData.cinemaId,
												"name": showData.cinemaName,
												"address": cinemaData.addr
											},
											"movie": {
												"id": movieId,
												"name": movie.detailMovie.nm,
												"img": movie.detailMovie.img
											},
											"seat": {
												"count": 1,
												"hallName": th,
												"list": [
													{
														"rowId": "5",
														"columnId": "06"
													},
												]
											},
											"show": {
												"language": lang,
												"endTime": endTime,
												"startTime": startTime
											}
										}
										//写入order
										let ordersPath = path.join(__dirname, '../data/orders.json');
										const ordersList = JSON.parse(fs.readFileSync(ordersPath, 'utf8'));
										ordersList.push(order)
										fs.writeFileSync(ordersPath, JSON.stringify(ordersList))

										res.json({
											code: 200,
											msg: "添加订单成功",
											data: {
												order: order
											}
										})
									}
								}
							}
							break
						}
					}
				}
			}
		} catch (e) {
			console.log(e);
		}

	}

	async getOrder(req, res, next) {
		const { orderId } = req.query;
		const ordersPath = path.join(__dirname, `../data/orders.json`);
		try {
			const orders = JSON.parse(fs.readFileSync(ordersPath, 'utf-8'))
			const order = orders.find(order => order.orderId === orderId)
			res.json({
				code: 200,
				msg: "查询订单成功",
				data: {
					order: order
				}
			})
		} catch (e) {
			res.json({
				code: 403,
				msg: "查询订单失败"
			})
		}
	}

	async delOrder(req, res, next) {
		const { orderId } = req.query;
		const ordersPath = path.join(__dirname, `../data/orders.json`);
		try {
			const orders = JSON.parse(fs.readFileSync(ordersPath, 'utf-8'))
			const index = orders.findIndex(order => order.orderId === orderId)
			const order = orders[index]
			orders.splice(index, 1)
			fs.writeFileSync(ordersPath, JSON.stringify(orders))

			res.json({
				code: 200,
				msg: "删除订单成功",
				data: {
					order: order
				}
			})
		} catch (error) {
			res.json({
				code: 403,
				msg: "删除订单失败",
				error
			})
		}
	}
}

module.exports = new OrdersController();